import { PageList } from "@mallfoundry/shared/data"
import { Member, MemberService } from "@mallfoundry/store/member"
import { useEffect, useState } from "react"

export function useMember(storeId: string, memberId: string) {
  const [member, setMember] = useState(new Member())
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    setLoading(true)
    MemberService
      .getMember({
        storeId, id: memberId,
      })
      .then(setMember)
      .finally(() => setLoading(false))
  }, [storeId, memberId])

  return {
    loading,
    member,
  }
}

interface UseMembersOptions {
  page?: string | number
  limit?: string | number
  storeId?: string
}

export function useMembers(options: UseMembersOptions) {
  const { page, limit, storeId } = options
  const [loading, setLoading] = useState(false)
  const [pageMembers, setPageMembers] = useState<PageList<Member>>(PageList.empty())

  useEffect(refresh, [page, limit, storeId])

  function refresh() {
    setLoading(true)

    MemberService.getMembers(
      MemberService.createMemberQuery()
        .toBuilder()
        .page(page)
        .limit(limit)
        .storeId(storeId)
        .build())
      .then(setPageMembers)
      .finally(() => setLoading(false))
  }

  return {
    loading,
    refresh,
    ...pageMembers,
  }
}
